'use strict';
let uniID = require('uni-id')
module.exports = {
	/**
	 * XXXnameXXX
	 * @url user/pub/loginBytt 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event,context) => {
		let token = event.uniIdToken
		console.log("token=",token);
		// uniID = uniID.createInstance({
		//   context
		// })
		const db = uniCloud.database();
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			openid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		// let uid = "62d9119f1341c70001d26689"
		// let updateUserres = await uniID.updateUser({
		//   uid:uid,
		//   nickname:"he"
		// });
		// console.log("updateUserres=",updateUserres);
		
		console.log("ttopenid=", openid);
		const user = await db.collection('uni-id-users').where({
			tt_openid: openid
		}).get()
		console.log("user=", user.data.length);
		if (user.data.length > 0) {
			res.data = user.data[0]
			return res;
		}

		if (user.data.length == 0) {
			//没查到用户时自动注册
			const registerUser = await db.collection('uni-id-users').add({
				tt_openid: openid,
				platform: "tt",
				balance: 0,
				plus_type: 0,
				register_date:new Date().getTime(),
				plus_expire_time: new Date().getTime(),
				status: 0,
				finish: {
					libao: false,
					jiesuo: false,
					shoujihao: false,
					dingyue: false,
					zhuomian: false,
					xinren: false,
				}
			})
			
			//注册完后自动拉取新用户信息并返回
			const getNewUser = await db.collection('uni-id-users').doc(registerUser.id).get()
			res.data = getNewUser.data[0]
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
